package com.jeeplus.modules.project.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.project.entity.BaseProjectInfo;
import com.jeeplus.modules.project.entity.ProjectApply;
import com.jeeplus.modules.project.service.BaseProjectInfoService;
import com.jeeplus.modules.project.service.ProjectApplyService;

/**
 * 项目申报表单Controller
 * @author jacky
 * @version 2017-12-10
 */
@Controller
@RequestMapping(value = "${adminPath}/project/projectApply")
public class ProjectApplyController extends BaseController {

	@Autowired
	private ProjectApplyService projectApplyService;
	@Autowired
	private BaseProjectInfoService baseProjectInfoService;
	
	@ModelAttribute
	public ProjectApply get(@RequestParam(required=false) String id) {
		ProjectApply entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = projectApplyService.get(id);
		}
		if (entity == null){
			entity = new ProjectApply();
		}
		return entity;
	}
	
	/**
	 * 项目申报表单列表页面
	 */
	@RequiresPermissions("project:projectApply:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProjectApply projectApply, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProjectApply> page = projectApplyService.findPage(new Page<ProjectApply>(request, response), projectApply); 
		model.addAttribute("page", page);
		return "modules/project/projectApply/projectApplyList";
	}

	/**
	 * 查看，增加，编辑项目申报表单表单页面
	 */
	@RequiresPermissions(value="project:projectApply:view")
	@RequestMapping(value = "form")
	public String form(ProjectApply projectApply,Model model) {
		String view = "projectApplyForm";
		// 查看审批申请单
		if (StringUtils.isNotBlank(projectApply.getId())){
			// 环节编号
			String taskDefKey = projectApply.getAct().getTaskDefKey();
			// 查看工单
			if(projectApply.getAct().isFinishTask()){
				view = "projectApplyViewForm";
			}else{
				view = "projectApplyAprovForm";
			}
		}else{
			//根据基本信息id 查询数据
			BaseProjectInfo pi = baseProjectInfoService.get(projectApply.getBasePtInfo().getId());
			projectApply.setBasePtInfo(pi);
		}
		
		model.addAttribute("apply", projectApply);
		return "modules/project/projectApply/"+view;
	}
	
	
	
	/**
	 * 保存项目申报表单
	 */
	@RequiresPermissions(value="project:projectApply:save")
	@RequestMapping(value = "save")
	public String save(ProjectApply projectApply, Model model, RedirectAttributes redirectAttributes) throws Exception{
		projectApplyService.save(projectApply);//保存
		addMessage(redirectAttributes, "提交审批'" + projectApply.getBasePtInfo().getHost() + "'成功");
		return "redirect:" + adminPath + "/act/task/todo/";
	}
	
	/**
	 * 工单执行（审核-完成任务）
	 * @param testAudit
	 * @param model
	 * @return
	 */
	@RequiresPermissions("project:projectApply:edit")
	@RequestMapping(value = "saveAprov")
	public String saveAprov(ProjectApply apply, Model model) {
		if (StringUtils.isBlank(apply.getAct().getFlag())
				|| StringUtils.isBlank(apply.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(apply, model);
		}
		projectApplyService.approveSave(apply);
		return "redirect:" + adminPath + "/act/task/todo/";
	}
	
	/**
	 * 删除项目申报表单
	 */
	@RequiresPermissions("project:projectApply:view")
	@RequestMapping(value = "delete")
	public String delete(ProjectApply projectApply, RedirectAttributes redirectAttributes) {
		projectApplyService.delete(projectApply);
		addMessage(redirectAttributes, "删除项目申报表单成功");
		return "redirect:"+Global.getAdminPath()+"/project/projectApply/?repage";
	}
	
	/**
	 * 批量删除项目申报表单
	 */
	@RequiresPermissions("project:projectApply:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			projectApplyService.delete(projectApplyService.get(id));
		}
		addMessage(redirectAttributes, "删除项目申报表单成功");
		return "redirect:"+Global.getAdminPath()+"/project/projectApply/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("project:projectApply:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(ProjectApply projectApply, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目申报表单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ProjectApply> page = projectApplyService.findPage(new Page<ProjectApply>(request, response, -1), projectApply);
    		new ExportExcel("项目申报表单", ProjectApply.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出项目申报表单记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/project/projectApply/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("project:projectApply:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ProjectApply> list = ei.getDataList(ProjectApply.class);
			for (ProjectApply projectApply : list){
				try{
					projectApplyService.save(projectApply);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条项目申报表单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条项目申报表单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入项目申报表单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/project/projectApply/?repage";
    }
	
	/**
	 * 下载导入项目申报表单数据模板
	 */
	@RequiresPermissions("project:projectApply:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目申报表单数据导入模板.xlsx";
    		List<ProjectApply> list = Lists.newArrayList(); 
    		new ExportExcel("项目申报表单数据", ProjectApply.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/project/projectApply/?repage";
    }
	
	
	

}